﻿using Api.Application.Command.Menu;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.Menu
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, ApiResult<int>>
    {
        private readonly IBase<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public DelMenuHandler(IBase<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public  async Task<ApiResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();

            var menu = menuRepo.GetAll().ToList();
            var count = await Dels(request.Id, menu);
            if(count>0)
            {
                result.Code = ApiEnum.OK;
                result.Msg = "删除成功";
            }
            else
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "删除失败";
            }
            result.Data = count;
            return await Task.FromResult(result);
        }
      
        public  async Task<int> Dels(int id, List<MenuModel> ids)
        {
            int count = 0;
            var res=ids.FirstOrDefault(x=>x.Id== id);
            if (res != null&&!res.IsDeleted)
            {
                res.IsDeleted = true;
                await menuRepo.Update(res);
                count++;
                var ress = ids.Where(x => x.PId == id && !x.IsDeleted).ToList();
                foreach (var item in ress)
                {
                    count +=await  Dels(item.Id, ids);
                }
            }
            return count;
        }
    }
}
